//
//  RHAccountViewController.m
//  RuiHeAppApp
//
//  Created by Jun on 2023/7/20.
//

#import "RHAccountViewController.h"
#import "RHChangePasswordController.h"
#import "RHChangeEmailViewController.h"
#import "RHAccountViewCell.h"
#import "RHLoginViewController.h"
#import "RHNavigationController.h"
#import <SDImageCache.h>
#import "NetworkConfig.h"
#import "RHDeviceModel.h"

@interface RHAccountViewController ()<UITableViewDelegate,UITableViewDataSource>

@property (nonatomic ,strong) UITableView *tableView;

@property (nonatomic ,strong) UIView *headerView;

@property (nonatomic ,strong) UIView *footerView;

@property (nonatomic, strong) NSArray *titles;
@end

@implementation RHAccountViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self.navigationItem setTitle:@"账号管理".rh_localized];
    [self.view setBackgroundColor:CFTabViewBgColor];
    
    
    [self setupUI];
}

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:NO animated:YES];
}

- (void)setupUI{
    self.titles = @[@"账号".rh_localized,@"修改密码".rh_localized,@"修改邮箱".rh_localized,@"清除缓存".rh_localized,@"删除账号".rh_localized];
    
    _tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStyleGrouped];
    [_tableView setBackgroundColor:UIColor.clearColor];
    [_tableView setSeparatorStyle:UITableViewCellSeparatorStyleNone];
    [_tableView setDelegate:self];
    [_tableView setDataSource:self];
    [_tableView registerClass:[RHAccountViewCell class] forCellReuseIdentifier:@"RHAccountViewCell"];
    _tableView.tableHeaderView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, kUI_WINDOW_W, 15)];
    [self.view addSubview:_tableView];
    
    QMUIButton *logoutBtn = [QMUIButton buttonWithType:UIButtonTypeCustom];
    [logoutBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [logoutBtn setTitle:@"退出登录".rh_localized forState:UIControlStateNormal];
    [logoutBtn.titleLabel setFont:[UIFont systemFontOfSize:16]];
    [logoutBtn.layer setCornerRadius:8];
    [logoutBtn setBackgroundColor:CMainColorGreen];
    [self.view addSubview:logoutBtn];
#pragma mark ----- 退出登录 ------
    [[logoutBtn rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
        [UserDefaults setBool:NO forKey:kIsLogined];
        [UserDefaults synchronize];
        [NetworkConfig sharedConfig].brandID = brand_id;//恢复通用品牌
        RHLoginViewController *Login_vc = [[RHLoginViewController alloc] init];
        RHNavigationController *login_nav = [[RHNavigationController alloc] initWithRootViewController:Login_vc];
        [[UIApplication sharedApplication].keyWindow setRootViewController:login_nav];

    }];
    
    [logoutBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_offset(15);
        make.right.mas_offset(-15);
        make.height.mas_equalTo(50);
        make.bottom.mas_offset(kSafe_bottom>0?-kSafe_bottom:-15);
    }];
    
    [_tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.top.right.mas_offset(0);
        make.bottom.equalTo(logoutBtn.mas_top).offset(-15);
    }];
    
}




#pragma mark - UITableViewDelegate,UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.titles.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 15;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    return nil;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 0;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
   return nil;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    RHAccountViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"RHAccountViewCell"];
    [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
    
    NSInteger bytesCache = [[SDImageCache sharedImageCache] totalDiskSize];
    NSString *cacheStr = [NSString stringWithFormat:@"%.1f M",bytesCache/1000.0/1000.0];
    NSString *userName = ValidNullDataToString([PrivateMange share].currentUser.userName, @"--");
    NSArray *contents = @[userName,@"",[PrivateMange share].currentUser.email,cacheStr,@""];
    [cell setTitleStr:self.titles[indexPath.row]];
    [cell setContentStr:contents[indexPath.row]];
    [cell hideLine:(indexPath.row == self.titles.count-1)];
    [cell hideArrow:indexPath.row == 0];
    if (indexPath.row == 0) {
        [cell setTopBorder];
    }else if (indexPath.row == self.titles.count - 1){
        [cell setBottomBorder];
    }else{
        [cell setMiddleBorder];
    }
    return cell;
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if(indexPath.row == 1){//修改密码
        RHChangePasswordController *vc = [[RHChangePasswordController alloc] init];
        [self.navigationController pushViewController:vc animated:YES];
    }
    
    if(indexPath.row == 2){//修改邮箱
        RHChangeEmailViewController *vc = [[RHChangeEmailViewController alloc] init];
        [self.navigationController pushViewController:vc animated:YES];
    }
    if(indexPath.row == 3){
        kWeakSelf;
        [QMUITips showLoadingInView:self.view];
        [[SDImageCache sharedImageCache]clearDiskOnCompletion:^{
            [QMUITips hideAllTipsInView:weakSelf.view];
            [QMUITips showSucceed:@"成功".rh_localized];
            [weakSelf.tableView reloadData];
        }];
    }
    
    if (indexPath.row == 4) {
        [self getDevList];
    }
}

//获取设备列表
- (void)getDevList{
    
    [QMUITips showLoadingInView:self.view];
    NSDictionary *para = @{@"userId":@([PrivateMange share].currentUser.userId),
                           @"pageNum":@(1),
                           @"pageSize":@(2)
    };
    [RHDeviceModel startGetWithCompletionAPIKey:H_deviceList argument:para  requestSuccess:^(__kindof BaseRequest *request, ResultModel *resultModel) {
            if (resultModel.code == 200) {
                NSArray *deviceList = resultModel.data;
                if(deviceList.count>0){
                    [QMUITips showInfo:@"请在删除帐号之前解绑设备".rh_localized];
                }else{
                    [self deleteAccountAction];
                }
            }
    } requestFail:^(__kindof BaseRequest *request, ResultModel *resultModel) {
       
        
    }];
}

- (void)deleteAccountAction{
    NSString *message = [NSString stringWithFormat:@"%@ %@?",@"确定删除此账号?".rh_localized,[PrivateMange share].currentUser.userName];
    QMUIAlertController *alertVC = [QMUIAlertController alertControllerWithTitle:@"删除账号".rh_localized message:message preferredStyle:QMUIAlertControllerStyleAlert];
    QMUIAlertAction *cancel = [QMUIAlertAction actionWithTitle:@"取消".rh_localized style:QMUIAlertActionStyleCancel handler:nil];
    kWeakSelf;
    QMUIAlertAction *sure = [QMUIAlertAction actionWithTitle:@"确定".rh_localized style:QMUIAlertActionStyleDestructive handler:^(__kindof QMUIAlertController * _Nonnull aAlertController, QMUIAlertAction * _Nonnull action) {
        [weakSelf deleteAccountRequest];
    }];
    [alertVC addAction:cancel];
    [alertVC addAction:sure];
    [alertVC showWithAnimated:YES];
}
#pragma mark -------- 删除账号
- (void)deleteAccountRequest{
    
    [QMUITips showLoadingInView:self.view];
    NSString *url = [NSString stringWithFormat:@"%@/%ld",H_deleteAccount,[PrivateMange share].currentUser.userId];
    [BaseModel startDeleteWithCompletionAPIKey:url argument:@{} requestSuccess:^(__kindof BaseRequest *request, ResultModel *resultModel) {
            if (resultModel.code == 200) {
                [UserDefaults setBool:NO forKey:kIsLogined];
                [UserDefaults synchronize];
                [NetworkConfig sharedConfig].brandID = brand_id;//恢复通用品牌
                NSString *bundleID = kbundleIdentifier;
                NSArray *accountList = [SAMKeychain accountsForService:bundleID];
                
                for (NSDictionary *dic in accountList) {
                    NSString *account = [dic objectForKey:@"acct"];
                    BOOL result = [SAMKeychain deletePasswordForService:bundleID account:account];
                    if (result) {
                        NSLog(@"---->删除钥匙串用户%@信息成功",account);
                    }else{
                        NSLog(@"---->删除钥匙串用户%@信息失败",account);
                    }
                }
               
               
                RHLoginViewController *Login_vc = [[RHLoginViewController alloc] init];
                RHNavigationController *login_nav = [[RHNavigationController alloc] initWithRootViewController:Login_vc];
                [[UIApplication sharedApplication].keyWindow setRootViewController:login_nav];
            }
        } requestFail:^(__kindof BaseRequest *request, ResultModel *resultModel) {
            
    }];
}

@end
